// https://github.com/github/fetch
// https://travis-ci.org/matthew-andrews/isomorphic-fetch
// https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

import fetch from 'isomorphic-fetch';
import cookie from 'js-cookie';
import qs from 'qs';
import {
    Message
} from 'antd';

const errorMessages = res => `${res.status} ${res.statusText}`;

function check404(res) {
    if (res.status === 404) {
        return Promise.reject(errorMessages(res));
    }
    return res;
}

function jsonParse(res) {
    return res.json().then(jsonResult => ({ ...res,
        jsonResult
    }));
}

function messageConfig() {
    Message.config({
        top: 100, // 消息距离顶部的位置
        duration: 2, // 默认自动关闭延时，单位秒
        maxCount: 1, // 最大显示数, 超过限制时，最早的消息会被自动关闭
    });
}

function errorMessageParse(res) {
    const {
        success,
        code,
        successful,
        error,
        error_code,
    } = res.jsonResult;
    // console.log(code);
    if (code != 200) {
        //Message.error( msg);
        if (code === 400) {
            // Message.error(error || '未登录请先登录', 1.5, () => { window.location.hash = '#/login';});
            if (error == '未登录') {
                messageConfig();
                Message.error(error || '未登录请先登录', 1.5, () => {
                    window.location.hash = '#/login';
                });
            } else {
                messageConfig();

            }



            // Message.error(message || '系统发生错误，未返回错误信息。', 1.5, () => { window.location.hash = '#/login';});
            if (error_code == 1001) {
                messageConfig();
                Message.error(error || '未登录请先登录', 1.5, () => {
                    window.location.hash = '#/login';
                });
            }
            // window.location.hash = '#/login'

        }
        return Promise.reject(error || '系统发生错误，未返回错误信息。');
    }
    return res;
}

function xFetch(url2, options) {
    const opts = {
        ...options,
        mode: 'cors',
        'Content-Type': 'application/json'
    };

    if (opts.method && opts.method.toUpperCase() === 'POST') {
        opts.headers = {
            'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
            ...opts.headers
        };
    } else if (!opts.method || (opts.method && opts.method.toUpperCase() === 'GET' && url2.indexOf('?') > -1)) {
        url2 += '&_input_charset=UTF-8';
    }

    function check401(res) {
        // location.href = '/401';
        if (res.status === 401) {
            console.log("认证错误！！")
        }
        return res;
    }

    return fetch(url2, opts)
        .then(check401)
        .then(check404)
        .then(jsonParse)
        .then(errorMessageParse)
        .catch((e) => {
            // fetch失败，多数为登录超时302跳转跨站异常，故此错误当登录超时处理
            // chrome错误：Network request failed
            // Safari错误：Network request failed
            return Promise.reject(`${e}`);
        });
}

// 自定义
function xFetchCustom(url2, options) {
    const opts = {
        ...options,
        'mode': 'cors',
        'Content-Type': 'application/json',
        credentials: 'include'
    };
    let access_token = sessionStorage.getItem('access_token') || '';
    let access_tokenParm = 'Bearer ' + access_token;
    // console.log(url2)
    if (opts.method && opts.method.toUpperCase() === 'POST') {
        opts.headers = {
            'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
            'Authorization': access_token ? access_tokenParm : 'Basic d2ViOjEyMzQ1Ng==',
            credentials: 'include',
            'headers': {
                'Accept': 'application/json'
            },
            ...opts.headers
        };
    } else if (!opts.method || (opts.method && opts.method.toUpperCase() === 'GET' && url2.indexOf('?') > -1)) {
        url2 += '&_input_charset=UTF-8';
    }

    function check401(res) {
        // location.href = '/401';
        if (res.status === 401) {
            console.log("认证错误！！")
        }
        return res;
    }


    return fetch(url2, opts)
        .then(jsonParse)
        .catch((e) => {
            // console.log(e)
            return Promise.reject(`${e}`);
        });
}


export const get = (url, params) => {
    return xFetch(`${url}?${qs.stringify(params)}`);
};
export const postCustom = (url, params) => {
    // let token = localStorage.getItem('token');
    // params.token = token;
    return xFetchCustom(url, {
        method: 'POST',
        body: qs.stringify(params)
    });
};

export const getCustom = (url, params) => {
    // let token = localStorage.getItem('token');
    // params.token = token;
    return xFetchCustom(`${url}?${qs.stringify(params)}`);
};

export const post = (url, params) => {
    return xFetch(url, {
        method: 'POST',
        body: qs.stringify(params)
    });
};

export default xFetch;